package mdb.com.vn.web.beans;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.Serializable;
import java.rmi.RemoteException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.xml.rpc.ServiceException;

import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;

import net.sf.jasperreports.engine.JREmptyDataSource;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import mdb.com.vn.model.FixedDepositCasa;
import mdb.com.vn.model.FixedDeposits;
import mdb.com.vn.model.LuckyDraw;
import mdb.com.vn.model.ScratchCard;
import mdb.com.vn.services.MDBServices;
import mdb.com.vn.utils.DateUtils;
import mdb.com.vn.utils.NumberUtils;
import mdb.com.vn.web.utils.FacesContextUtils;
import mdb.com.vn.wservices.utils.FixedDepositsFromT24;

@ManagedBean(name = "requestBean")
@ViewScoped
public class RequestBean implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private String savingBookNo;
	private int number00k;
	private int number20k;
	private int number50k;
	private int number100k;
	private int number200k;
	private int number500k;

	private String detail20k;
	private String detail50k;
	private String detail100k;
	private String detail200k;
	private String detail500k;

	private FixedDeposits fixedDeposits;
	private StreamedContent file;

	private boolean btnVisible;
	private boolean btnSaveVisible;
	private int totalScradAvailable;
	private double totalAmountAvailable;

	@ManagedProperty("#{mdbServices}")
	private MDBServices mdbServices;

	@PostConstruct
	public void init() {
		savingBookNo = "";
		fixedDeposits = new FixedDeposits();
		fixedDeposits.setCheckGetVGift(true);
	}

	public void searchFDfromT24P() throws Exception {
		fixedDeposits = new FixedDeposits();
		fixedDeposits.setCheckGetVGift(true);
		try {
			if (savingBookNo.equals("")) {
				FacesContext.getCurrentInstance().addMessage(
						null,
						new FacesMessage(FacesMessage.SEVERITY_WARN,
								"Nhập số sổ tiết kiệm là thông tin bắt buộc!",
								"Vui lòng nhập lại"));
			} else {
				if (savingBookNo.substring(0, 1).equals("6")
						&& savingBookNo.length() == 11) {

					FixedDeposits deposits = mdbServices
							.findFixedDepositsByCode(savingBookNo);
					FixedDepositCasa depositCasa = mdbServices
							.findFixedDepositCasaByCodeFD(savingBookNo);
					
					if (deposits != null || depositCasa != null) {
						fixedDeposits.setLuckyDraw(0);
						fixedDeposits.setScCard(0);
						setBtnSaveVisible(false);
						FacesContext
								.getCurrentInstance()
								.addMessage(
										null,
										new FacesMessage(
												FacesMessage.SEVERITY_WARN,
												"Tài khoản này đã tham chương trình khuyến mãi rồi ",
												"Vui lòng xem lại thể lệ chương trình"));
					} else {
						fixedDeposits = FixedDepositsFromT24.getFDInfoFromT24(
								fixedDeposits, savingBookNo);
						Date startDate = fixedDeposits.getStartDate();
						Date promotion = DateUtils
								.createDateYYYYMMDD("20131209");
						if (fixedDeposits.getLuckyDraw() == 0
								|| startDate.compareTo(promotion) < 0) {
							setBtnSaveVisible(false);
							FacesContext
									.getCurrentInstance()
									.addMessage(
											null,
											new FacesMessage(
													FacesMessage.SEVERITY_WARN,
													"Thông tin không đúng hoặc không đủ điều kiện tham gia chương trình khuyến mãi! ",
													"Vui lòng kiểm tra lại hoặc xem thể lệ chương trình"));
						} else {
							int ldrAvailble = mdbServices
									.getSCardFDAvailable(fixedDeposits
											.getCustomerId())
									+ mdbServices
											.getSCardCSAvailable(fixedDeposits
													.getCustomerId())
									+ mdbServices
											.getSCardFDCSAvailable(fixedDeposits
													.getCustomerId());
							setTotalScradAvailable(ldrAvailble);
							if (fixedDeposits.getCustomerType() == 1
									&& fixedDeposits.getInterestRate() != 7.5) {
								int tocalculatebag = fixedDeposits.getScCard()
										+ getTotalScradAvailable();
								fixedDeposits.setBagGift(tocalculatebag / 5);
								fixedDeposits.setTrayGift(tocalculatebag / 10);
							}

							if (fixedDeposits.getCustomerType() == 2
									&& fixedDeposits.getInterestRate() != 7.5) {
								int tocalculatebag = fixedDeposits.getScCard()
										+ getTotalScradAvailable();
								fixedDeposits
										.setVoucherGiftMore(tocalculatebag / 30);
							}
							if (fixedDeposits.getCustomerType() == 2) {
								setTotalAmountAvailable(mdbServices
										.getAmountCorpAvailable(fixedDeposits
												.getCustomerId()));
							}

							// ///////////////////////////////////////
							if (fixedDeposits.getCustomerType() == 1 && fixedDeposits.getInterestRate() == 7.5) {
								fixedDeposits.setBagGift(getTotalScradAvailable() / 5);
								fixedDeposits.setTrayGift(getTotalScradAvailable() / 10);
								fixedDeposits.setScCardNotGet(0);
							}
							if (fixedDeposits.getCustomerType() == 2 && fixedDeposits.getInterestRate() == 7.5) {
								fixedDeposits.setVoucherGiftMore(getTotalScradAvailable() / 30);
								fixedDeposits.setScCardNotGet(0);
							}
							/////////////////////////////////////////

							setBtnSaveVisible(true);
						}
					}
				} else {
					setBtnSaveVisible(false);
					FacesContext
							.getCurrentInstance()
							.addMessage(
									null,
									new FacesMessage(
											FacesMessage.SEVERITY_WARN,
											"Không đúng định dạng của số Sổ tiết kiệm ",
											"Vui lòng nhập lại 11 chữ số và chữ số đầu tiên là 6"));
				}
			}

		} catch (RemoteException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ServiceException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	public void addNewFDP() {
		int total_sc = number00k + number20k + number50k + number100k
				+ number200k + number500k;
		int total_sc_full = fixedDeposits.getScCard()
				+ getTotalScradAvailable();
		int bagReceived = fixedDeposits.getBgiftReceived();
		int trayReceived = fixedDeposits.getTgiftReceived();
		int vcherReceived = fixedDeposits.getVoucherGiftMore();
		bagReceived = bagReceived * 5;
		trayReceived = trayReceived * 10;
		vcherReceived = vcherReceived * 30;
		int total_sc_received = bagReceived + trayReceived + vcherReceived;

		if (total_sc > fixedDeposits.getScCard()
				|| total_sc_received > total_sc_full) {
			setBtnSaveVisible(true);
			FacesContext
					.getCurrentInstance()
					.addMessage(
							null,
							new FacesMessage(
									FacesMessage.SEVERITY_WARN,
									"Vượt quá số lượng áo thun, khay mứt và thẻ cào cho phép ",
									"Vui lòng nhập lại"));
		} else {

			if (total_sc == fixedDeposits.getScCard()) {
				try {
					fixedDeposits.setScCardNotGet(fixedDeposits.getScCard()
							- total_sc_received);
					mdbServices.addFixedDeposits(fixedDeposits);
					for (int i = 0; i < fixedDeposits.getLuckyDraw(); i++) {
						LuckyDraw luckyDraw = new LuckyDraw();
						luckyDraw.setCustomerRef(fixedDeposits.getCustomerId());
						luckyDraw.setTransRef(fixedDeposits.getSavingbookNo());
						luckyDraw
								.setLdrDesription("Số dự thưởng cho "
										+ fixedDeposits.getCustomerName());
						luckyDraw.setStatus(1);
						luckyDraw.setCreatedBy(fixedDeposits.getCreatedBy());
						luckyDraw.setDateCreated(new Date());
						mdbServices.addLuckyDraw(luckyDraw);
					}
					if (number20k > 0) {
						ScratchCard scratchCard = new ScratchCard();
						scratchCard
								.setTransRef(fixedDeposits.getSavingbookNo());
						scratchCard.setCreatedBy(fixedDeposits.getCreatedBy());
						scratchCard.setDateCreated(new Date());
						scratchCard.setScDesription(detail20k);
						scratchCard.setCustomerRef(fixedDeposits
								.getCustomerId());
						scratchCard.setStatus(1);
						scratchCard.setScDenomination(20000);
						scratchCard.setQuantity(number20k);
						mdbServices.addScratchCard(scratchCard);
					}
					if (number50k > 0) {
						ScratchCard scratchCard = new ScratchCard();
						scratchCard
								.setTransRef(fixedDeposits.getSavingbookNo());
						scratchCard.setCreatedBy(fixedDeposits.getCreatedBy());
						scratchCard.setDateCreated(new Date());
						scratchCard.setScDesription(detail50k);
						scratchCard.setCustomerRef(fixedDeposits
								.getCustomerId());
						scratchCard.setStatus(1);
						scratchCard.setScDenomination(50000);
						scratchCard.setQuantity(number50k);
						mdbServices.addScratchCard(scratchCard);

					}
					if (number100k > 0) {
						ScratchCard scratchCard = new ScratchCard();
						scratchCard
								.setTransRef(fixedDeposits.getSavingbookNo());
						scratchCard.setCreatedBy(fixedDeposits.getCreatedBy());
						scratchCard.setDateCreated(new Date());
						scratchCard.setScDesription(detail100k);
						scratchCard.setCustomerRef(fixedDeposits
								.getCustomerId());
						scratchCard.setStatus(1);
						scratchCard.setScDenomination(100000);
						scratchCard.setQuantity(number100k);
						mdbServices.addScratchCard(scratchCard);

					}
					if (number200k > 0) {
						ScratchCard scratchCard = new ScratchCard();
						scratchCard
								.setTransRef(fixedDeposits.getSavingbookNo());
						scratchCard.setCreatedBy(fixedDeposits.getCreatedBy());
						scratchCard.setDateCreated(new Date());
						scratchCard.setScDesription(detail200k);
						scratchCard.setCustomerRef(fixedDeposits
								.getCustomerId());
						scratchCard.setStatus(1);
						scratchCard.setScDenomination(200000);
						scratchCard.setQuantity(number200k);
						mdbServices.addScratchCard(scratchCard);

					}
					if (number500k > 0) {
						ScratchCard scratchCard = new ScratchCard();
						scratchCard
								.setTransRef(fixedDeposits.getSavingbookNo());
						scratchCard.setCreatedBy(fixedDeposits.getCreatedBy());
						scratchCard.setDateCreated(new Date());
						scratchCard.setScDesription(detail500k);
						scratchCard.setCustomerRef(fixedDeposits
								.getCustomerId());
						scratchCard.setStatus(1);
						scratchCard.setScDenomination(500000);
						scratchCard.setQuantity(number500k);
						mdbServices.addScratchCard(scratchCard);

					}
					if (number00k > 0) {
						fixedDeposits.setCheckGetThankSC(number00k);
					}
					// /////////////////////////
					String fileName = fixedDeposits.getSavingbookNo() + ".pdf";
					Map<String, Object> data = new HashMap<String, Object>();

					data.put("BranchID", fixedDeposits.getBranchCode());
					data.put("CustomerID", fixedDeposits.getCustomerId());
					data.put("CustomerName", fixedDeposits.getCustomerName());
					data.put("SavingBookNo", fixedDeposits.getSavingbookNo());
					data.put("FDAmount", NumberUtils.format(fixedDeposits
							.getAmount().toString(), "###,###,###,###"));
					data.put("FDTerm", fixedDeposits.getTerm());
					data.put("FDInterest",
							Double.toString(fixedDeposits.getInterestRate()));
					data.put("TotalSCard", fixedDeposits.getScCard());
					data.put("TotalLDR", fixedDeposits.getLuckyDraw());

					data.put("BranchName",
							mdbServices.getCompanyNameByCode(fixedDeposits
									.getBranchCode()));
					data.put(
							"LuckyDrawCodes",
							mdbServices.getAllLuckyDrawCodeP(
									fixedDeposits.getSavingbookNo(), 0));

					List<ScratchCard> scratchCards = mdbServices
							.getScratchCardByRef(fixedDeposits
									.getSavingbookNo());
					double totalSCAmount = 0;
					for (ScratchCard scratchCard : scratchCards) {
						if (scratchCard.getScDenomination() == 20000) {
							data.put("Card20k", scratchCard.getQuantity());
							totalSCAmount += scratchCard.getQuantity() * 20000;
						}
						if (scratchCard.getScDenomination() == 50000) {
							data.put("Card50k", scratchCard.getQuantity());
							totalSCAmount += scratchCard.getQuantity() * 50000;
						}
						if (scratchCard.getScDenomination() == 100000) {
							data.put("Card100k", scratchCard.getQuantity());
							totalSCAmount += scratchCard.getQuantity() * 100000;
						}
						if (scratchCard.getScDenomination() == 200000) {
							data.put("Card200k", scratchCard.getQuantity());
							totalSCAmount += scratchCard.getQuantity() * 200000;
						}
						if (scratchCard.getScDenomination() == 500000) {
							data.put("Card500k", scratchCard.getQuantity());
							totalSCAmount += scratchCard.getQuantity() * 500000;
						}
					}
					data.put("TotalSCAmount", NumberUtils.format(totalSCAmount,
							"###,###,###,###"));
					data.put(
							"ImagesPath",
							FacesContextUtils
									.getResourcePath("/WEB-INF/classes/mdb/com/vn/web/reports/MDB.jpg"));

					FixedDeposits deposits = mdbServices
							.findFixedDepositsByCode(fixedDeposits
									.getSavingbookNo());
					if (fixedDeposits.getInterestRate() == 7.5) {
						fixedDeposits.setScCardNotGet(0 - total_sc_received);
					}
					if (fixedDeposits.getCustomerType() == 1) {
						fixedDeposits.setId(deposits.getId());
						data.put("ThanksCard",
								fixedDeposits.getCheckGetThankSC());
						fixedDeposits.setScCardAmt(totalSCAmount);
						data.put("TshirtGift", fixedDeposits.getBgiftReceived());
						data.put("TrayGift", fixedDeposits.getTgiftReceived());

						mdbServices.updateFixedDeposits(fixedDeposits);

						JasperReport jasperReport = JasperCompileManager
								.compileReport(FacesContextUtils
										.getResourcePath("/WEB-INF/classes/mdb/com/vn/web/reports/FDReport.jrxml"));

						JasperPrint jasperPrint = JasperFillManager.fillReport(
								jasperReport, data, new JREmptyDataSource());

						JasperExportManager.exportReportToPdfFile(jasperPrint,
								fileName);
					}
					if (fixedDeposits.getCustomerType() == 2) {
						double temPSCAmount = totalSCAmount
								+ getTotalAmountAvailable();

						int voucherGift = (int) (temPSCAmount / 100000);
						fixedDeposits.setId(deposits.getId());
						fixedDeposits.setVoucherGift(voucherGift);
						fixedDeposits.setScCardAmt(totalSCAmount);
						fixedDeposits.setScCardAmtNot(totalSCAmount
								- (voucherGift * 100000));

						data.put("ThanksCard",
								fixedDeposits.getCheckGetThankSC());
						mdbServices.updateFixedDeposits(fixedDeposits);
						data.put("VoucherGift", voucherGift);
						data.put("VoucherGiftMore",
								fixedDeposits.getVoucherGiftMore());
						JasperReport jasperReport = JasperCompileManager
								.compileReport(FacesContextUtils
										.getResourcePath("/WEB-INF/classes/mdb/com/vn/web/reports/FDSMEReport.jrxml"));

						JasperPrint jasperPrint = JasperFillManager.fillReport(
								jasperReport, data, new JREmptyDataSource());

						JasperExportManager.exportReportToPdfFile(jasperPrint,
								fileName);
					}

					File filetemps = new File(fileName);
					InputStream fis = new FileInputStream(filetemps);
					file = new DefaultStreamedContent(fis, "application/pdf",
							fileName);
					filetemps = new File(filetemps.getCanonicalPath());
					filetemps.delete();
					setBtnVisible(true);
					setBtnSaveVisible(false);
					FacesContext.getCurrentInstance().addMessage(
							null,
							new FacesMessage(FacesMessage.SEVERITY_INFO,
									"Lưu thông tin thành công",
									"Bấm nút 'In phiếu thông tin' để in phiếu thông tin cho khách hàng"));

				} catch (Exception e) {
					setBtnSaveVisible(true);
					FacesContext.getCurrentInstance().addMessage(
							null,
							new FacesMessage(FacesMessage.SEVERITY_ERROR,
									"Lỗi xảy ra trong qua trình nhập liệu",
									"Vui lòng kiểm tra lại"));
					e.printStackTrace();
				}
			} else {
				setBtnSaveVisible(true);
				FacesContext.getCurrentInstance().addMessage(
						null,
						new FacesMessage(FacesMessage.SEVERITY_WARN,
								"Nhập chưa đầy đủ số lượng thẻ cào",
								"Vui lòng kiểm tra lại"));

			}

		}
	}

	public void testBTN() {
		setBtnVisible(true);
		file = null;
	}

	public String getSavingBookNo() {
		return savingBookNo;
	}

	public void setSavingBookNo(String savingBookNo) {
		this.savingBookNo = savingBookNo;
	}

	public FixedDeposits getFixedDeposits() {
		return fixedDeposits;
	}

	public void setFixedDeposits(FixedDeposits fixedDeposits) {
		this.fixedDeposits = fixedDeposits;
	}

	public void setMdbServices(MDBServices mdbServices) {
		this.mdbServices = mdbServices;
	}

	public int getNumber20k() {
		return number20k;
	}

	public void setNumber20k(int number20k) {
		this.number20k = number20k;
	}

	public int getNumber50k() {
		return number50k;
	}

	public void setNumber50k(int number50k) {
		this.number50k = number50k;
	}

	public int getNumber100k() {
		return number100k;
	}

	public void setNumber100k(int number100k) {
		this.number100k = number100k;
	}

	public int getNumber200k() {
		return number200k;
	}

	public void setNumber200k(int number200k) {
		this.number200k = number200k;
	}

	public int getNumber500k() {
		return number500k;
	}

	public void setNumber500k(int number500k) {
		this.number500k = number500k;
	}

	public String getDetail20k() {
		return detail20k;
	}

	public void setDetail20k(String detail20k) {
		this.detail20k = detail20k;
	}

	public String getDetail50k() {
		return detail50k;
	}

	public void setDetail50k(String detail50k) {
		this.detail50k = detail50k;
	}

	public String getDetail100k() {
		return detail100k;
	}

	public void setDetail100k(String detail100k) {
		this.detail100k = detail100k;
	}

	public String getDetail200k() {
		return detail200k;
	}

	public void setDetail200k(String detail200k) {
		this.detail200k = detail200k;
	}

	public String getDetail500k() {
		return detail500k;
	}

	public void setDetail500k(String detail500k) {
		this.detail500k = detail500k;
	}

	public MDBServices getMdbServices() {
		return mdbServices;
	}

	public StreamedContent getFile() {
		try {
			return file;
		} catch (Exception e) {
			// TODO: handle exception
			return null;
		}

	}

	public boolean isBtnVisible() {
		return btnVisible;
	}

	public void setBtnVisible(boolean btnVisible) {
		this.btnVisible = btnVisible;
	}

	public boolean isBtnSaveVisible() {
		return btnSaveVisible;
	}

	public void setBtnSaveVisible(boolean btnSaveVisible) {
		this.btnSaveVisible = btnSaveVisible;
	}

	public int getTotalScradAvailable() {
		return totalScradAvailable;
	}

	public void setTotalScradAvailable(int totalScradAvailable) {
		this.totalScradAvailable = totalScradAvailable;
	}

	public double getTotalAmountAvailable() {
		return totalAmountAvailable;
	}

	public void setTotalAmountAvailable(double totalAmountAvailable) {
		this.totalAmountAvailable = totalAmountAvailable;
	}

	public int getNumber00k() {
		return number00k;
	}

	public void setNumber00k(int number00k) {
		this.number00k = number00k;
	}

}
